<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>平台信息</span>
        </div>
      </template>
      <div class="tips-row">
        <div class="tips-col">
          <div class="tips-name">授权日期：</div>
          <div class="tips-value">{{date.formatLongDate(license.licenseTime, 'yyyy-MM-dd')}}</div>
        </div>
        <div class="tips-col">
          <div class="tips-name">授权版本：</div>
          <div class="tips-value">{{license.licenseVersion}}</div>
        </div>
        <div class="tips-col">
          <div class="tips-name">当前版本：</div>
          <div class="tips-value">{{version.version}}</div>
        </div>
      </div>
      <div class="tips-row">
        <div class="tips-col">
          <div class="tips-name">失效日期：</div>
          <div class="tips-value">{{date.formatLongDate(license.expireTime, 'yyyy-MM-dd')}}</div>
        </div>
        <div class="tips-col">
          <div class="tips-name">发布时间：</div>
          <div class="tips-value">{{version.publishDate}}</div>
        </div>
        <div class="tips-col">
          <div class="tips-name">分支 / 版本：</div>
          <div class="tips-value">{{version.branch}} / {{version.branchVersion}}</div>
        </div>
      </div>
      <div class="tips-row">
        <div class="tips-col">
          <div class="tips-name">剩余时间：</div>
          <div class="tips-value">
            <span class="color-blue">{{date.getDiffPeriod(license.licenseTime, license.expireTime)}}</span>
          </div>
        </div>
      </div>
      <div class="tips-row">
        <div class="tips-center">
          <el-button type="primary" @click="machineVisible=true">获取机器码</el-button>
          <el-button type="success" @click="showLicenseDialog">更新授权码</el-button>
        </div>
      </div>
    </el-card>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>运行情况</span>
        </div>
      </template>
      <div class="tips-row">
        <div class="tips-col">
          <div class="tips-name">启动时间：</div>
          <div class="tips-value">{{date.formatLongDate(session.startTime, 'yyyy-MM-dd HH:mm:ss')}}</div>
        </div>
        <div class="tips-col no-width">
          <div class="tips-name">运行时长：</div>
          <div class="tips-value">{{date.getDiffTime(session.startTime, session.endTime)}}</div>
        </div>
        <div class="tips-col">
          <div class="tips-name">当前在线人数：</div>
          <div class="tips-value">
            <span class="color-blue pointer" @click="showOnlineDialog">{{session.onlineCount}}</span> 人
          </div>
        </div>
      </div>
      <div class="tips-row">
        <div ref="loginChart" style="width: 100%; height: 400px;"></div>
      </div>
    </el-card>
  </div>

  <!-- 显示机器码 -->
  <el-dialog
    title="机器码"
    width="600px"
    v-model="machineVisible"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <div>{{license.machineCode}}</div>
    <template #footer>
      <el-button
        size="default"
        type="primary"
        @click="machineVisible=false"
      >确定</el-button>
    </template>
  </el-dialog>

  <!-- 显示授权码 -->
  <el-dialog
    title="更新授权码"
    width="600px"
    v-model="licenseVisible"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="licenseDataForm"
      class="no-padding"
      label-width="0"
      label-position="right"
      :model="licenseFormData"
      :rules="licenseRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="" prop="license">
            <el-input type="textarea" :rows="8" v-model="licenseFormData.license"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="licenseVisible=false"
      >取消</el-button>
      <el-button
        size="default"
        type="primary"
        @click="submitLicense"
        :loading="licenseEditLoading"
      >确定</el-button>
    </template>
  </el-dialog>

  <el-dialog
    title="在线人员"
    v-model="onlineVisible"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
    fullscreen
  >
    <ac-table
      ref="dataTable"
      pkName="id"
      :filters="filters"
      :filterFields="filterFields"
      dataUrl="/system/session/onlineList"
      :columns="columns"
      @handleCellOperator="handleCellOperator"
    ></ac-table>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="onlineVisible=false"
      >关闭</el-button>
    </template>
  </el-dialog>

  <el-dialog
    title="人员信息"
    width="800px"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <ac-form
      ref="dataForm"
      v-model="formData"
      :fields="formColumns"
      :disabled="true"
    />
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="dialogVisible = false"
      >关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/http/api';
import date from '@/utils/date';
import * as echarts from 'echarts';

const license = ref({});
const version = ref({});
const session = ref({});

const machineVisible = ref(false);
const licenseDataForm = ref();
const licenseFormData = ref({});
const licenseVisible = ref(false);
const licenseEditLoading = ref(false);
const licenseRules = ref({
  license: [
    {required: true, message: '请输入授权码', trigger: 'blur'},
  ]
});

const onlineVisible = ref(false);
const dataTable = ref();
const filters = ref({
  name: "",
});
const filterFields = ref([
  {prop: "name", label: "姓名"},
]);
const columns = ref([
  {prop: "username", label: "登录账号", minWidth: 160, sortable: false, click: true},
  {prop: "name", label: "姓名", minWidth: 120, sortable: false},
  {prop: "sex", label: "性别", width: 120, type: 'dict-select', dictCode: 'dictSex', sortable: false},
  {prop: "sessionId", label: "登录标识", width: 300, sortable: false},
  {prop: "loginIp", label: "IP地址", width: 160, sortable: false},
  {prop: "loginTime", label: "登录时间", width: 160, sortable: false, type: "datetime"},
  {prop: "loginTime", label: "操作", width: 100, sortable: false, click: true, formatter: () => '强制下线'},
]);
const formColumns = ref([
  {prop: "name", label: "姓名", minWidth: 90, click: true},
  {prop: "sex", label: "性别", minWidth: 80, type: 'dict-radio', dictCode: 'dictSex'},
  {prop: "username", label: "登录账号", minWidth: 110},
  {prop: "organizationId", label: "默认部门", minWidth: 140, type: 'organization'},
  {prop: "belongIds", label: "归属部门", minWidth: 140, table: false, type: 'organization', leafSelect: false, multiple: true, appendToBody: true},
  {prop: "ordinal", label: "排序", width: 90, type: 'number'},
  {prop: "valid", label: "是否有效", width: 90, sortable: false, type: 'dict-radio', dictCode: "dictYesNo"},
  {prop: "loginTime", label: "登录时间", width: 160, sortable: false, type: "datetime"},
  {prop: "updateTime", label: "更新时间", minWidth: 160, onlyShow: true, type: "datetime"},
  {prop: "createTime", label: "创建时间", minWidth: 160, onlyShow: true, table: false, type: "datetime"},
])
const dialogVisible = ref(false);
const formData = ref({});

const loginChart = ref();

const loadLicense = () => {
  api.post("/license/queryBy").then(res => {
    license.value = res.data || {};
  });
};

const loadVersion = () => {
  api.post("/system/version/queryBy").then(res => {
    version.value = res.data || {};
  });
};

const loadSession = () => {
  api.post("/system/session/info").then(res => {
    session.value = res.data || {};
  });
};

const showOnlineDialog = () => {
  onlineVisible.value = true;
};

const handleCellOperator = (property, value, row) => {
  if (property === 'username') {
    dialogVisible.value = true;
    formData.value = row;
    return;
  }

  ElMessageBox.confirm('请确认是否强制该用户【' + row.name + '】下线？', '提示', {type: 'info'}).then(() => {
    licenseEditLoading.value = true;
    api.post("/system/session/forceOffline", row).then(res => {
      ElMessage.success(res.message);
      dataTable.value.findPage();
    });
  }).catch(()=>{});
}

const showLicenseDialog = () => {
  licenseFormData.value.license = '';
  licenseVisible.value = true;
}

const submitLicense = () => {
  licenseDataForm.value && licenseDataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否更新授权码？', '提示', {type: 'info'}).then(() => {
        licenseEditLoading.value = true;
        api.post("/license/updateLicense", licenseFormData.value).then(res => {
          ElMessage.success(res.message);
          loadLicense();
          licenseVisible.value = false;
          licenseEditLoading.value = false;
        }).catch(() => {
          licenseEditLoading.value = false;
        });
      }).catch(()=>{});
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};

const loadLoginData = () => {
  api.post("/system/loginLog/queryMonthStatList").then(res => {
    initChart(res.data || []);
  });
};

const initChart = (dataList) => {
  const loginDates = [];
  const loginMans = [];
  const loginTimes = [];
  dataList.forEach((item) => {
    loginDates.push(item.loginDate);
    loginMans.push(item.loginMans);
    loginTimes.push(item.loginTimes);
  });

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      }
    },
    grid: {
      top: '20px',
      left: '20px',
      right: '20px',
      bottom: '20px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: loginDates
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '登录人数',
        showSymbol: false,
        smooth: true,
        data: loginMans,
        type: 'line',
        areaStyle: {
        },
      },
      {
        name: '登录次数',
        showSymbol: false,
        smooth: true,
        data: loginTimes,
        type: 'bar',
        barWidth: '30px',
      }
    ]
  };

  echarts.init(loginChart.value).setOption(option);
};

onMounted(() => {
  loadLicense();
  loadVersion();
  loadSession();
  loadLoginData();
});
</script>

<style scoped lang="scss">
.page-container {
  display: block;
  :deep(.el-card) {
    .el-card__header {
      background-color: #268ff2!important;
      .card-header {
        font-size: 16px;
        font-weight: bold;
        color: white;
      }
    }
  }
}
.tips-row {
  font-size: 16px;
  display: flex;
  flex-direction: row;
  margin-bottom: 30px;
  .tips-col {
    width: 220px;
    margin-right: 40px;
    display: flex;
    flex-direction: row;
    .tips-name, .tips-value {
      white-space: nowrap;
    }
    .color-blue {
      color: #0085f6;
    }
  }
  .no-width {
    width: unset!important;
  }
  .tips-center {
    margin-left: 30px;
  }
}
.tips-row:last-child {
  margin-bottom: 10px;
}
</style>